<template>
  <div>
    <el-dialog
      title="查看监控"
      width="40%"
      :visible.sync="dialogVisible"
      :before-close="handleCancel"
      center
      :close-on-press-escape="false"
    >
      <div class="dialog-device-info">
        <video-player
          v-if="showPlayer"
          class="video-player vjs-custom-skin"
          id="videoDialog"
          ref="videoPlayer"
          :options="playerOptions"
          :playsinline="true"
        >
        </video-player>
        <div v-else class="no-video">
          <a>暂无视频</a>
        </div>

        <ul class="video-bar" flex="dir:left" v-if="showTabs">
          <li
            v-for="(item, index) in eqptList"
            v-bind:key="index"
            @click="handleVideoIndex(item, index)"
            :class="{ active: index === videoIndex }"
          >
            {{ item.equipmentName }}
          </li>
        </ul>

        <div class="catchBtn">
          <span>图片抓拍：</span>
          <el-button type="primary" :loading="loading" @click="catchPhoto" size="small">点击抓拍</el-button>
        </div>
        <div class="shop-upload">
          <viewer :images="imgList" class="img-con">
            <img v-for="(item, index) in imgList" :src="item" :key="index" class="monitor-img" />
          </viewer>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getEquipmentList } from '../js/patrol'
import { eqptCommon } from '../js/monitor'

export default {
  name: 'MonitorModal',
  data () {
    return {
      dialogVisible: false,
      playerOptions: {
        muted: false,
        autoplay: true,
        preload: 'auto',
        fluid: true,
        techOrder: ['html5'], // 兼容顺序
        notSupportedMessage: '此视频暂无法播放，请稍后再试',
        aspectRatio: '16:9',
        language: 'zh-CN',
        sources: [
          {
            withCredentials: false,
            type: 'application/x-mpegURL',
            src: ''
          }
        ],
        html5: {
          hls: {
            withCredentials: false
          }
        },
        controlBar: {
          progressControl: false, // 进度条
          timeDivider: false, // 当前时间和持续时间的分隔符
          durationDisplay: false, // 显示持续时间
          remainingTimeDisplay: false, // 是否显示剩余时间功能
          fullscreenToggle: true // 全屏按钮
        }
      },
      eqptList: [], // 设备列表
      activeEqptId: '', // 激活的设备id
      eqptQueryParams: {}, // 查询条件
      videoIndex: 0,
      showPlayer: false, // 是否显示播放容器
      imgList: [],
      loading: false,
      showTabs: false
    }
  },
  watch: {
    activeEqptId (val) {
      if (val) {
        this.getAddress()
        this.timer = setInterval(() => {
          this.heartbeat()
        }, 20000)
      }
    }
  },
  methods: {
    // 弹框
    open (record) {
      this.dialogVisible = true
      if (record.length) {
        this.eqptList = record
        this.assignment(this.eqptList[0])
      } else {
        this.showTabs = true
        this.getEqptList()
      }
    },

    // 初始化视频列表数据
    async getEqptList () {
      const params = {
        pageNum: 1,
        pageSize: 100000
      }
      const { data } = await getEquipmentList(params)
      this.eqptList = this.formartData(data.list)
      this.assignment(this.eqptList[0])
    },
    // 格式化数组
    formartData (arr) {
      let list = []
      arr.map(item => {
        list.push(this.$pick(item, 'equipmentName', 'equipmentId', 'businessUserId', 'streamInfoId'))
      })
      return list
    },
    // 赋值
    assignment (obj) {
      const { equipmentId, streamInfoId: channelId, businessUserId } = obj
      this.eqptQueryParams = { businessUserId, channelId }
      this.activeEqptId = equipmentId
    },
    // 获取流地址
    async getAddress () {
      const params = {
        dataSign: 'TNT1603699784785-SERV1605252527969',
        endTime: 0,
        params: { ...this.eqptQueryParams, streamProtocol: '3' },
        startTime: 0
      }
      const data = await eqptCommon(params)
      let res = JSON.parse(data.data)
      if (res.code === 0) {
        this.$set(this.playerOptions.sources[0], 'src', res.data ? res.data.address : '')
        this.showPlayer = true
        this.plugFlow()
      }
    },

    // 推流
    async plugFlow () {
      const params = {
        dataSign: 'TNT1603699784785-SERV1605252561868',
        endTime: 0,
        // params: {
        //   channelId: '8d7fb6ed432eb11a4a2a53d11d1e6fb4',
        //   businessUserId: 'f4a226004246932ca32272463f31ab9b',
        //   liveNeedOn: '1'
        // },
        params: { ...this.eqptQueryParams, liveNeedOn: '1' },
        startTime: 0
      }
      await eqptCommon(params)
    },
    // 保活
    async heartbeat () {
      const params = {
        dataSign: 'TNT1603699784785-SERV1605252611439',
        endTime: 0,
        params: { ...this.eqptQueryParams, liveNeedOn: '1' },
        startTime: 0
      }
      await eqptCommon(params)
    },

    // 切换视频
    handleVideoIndex (row, index) {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
      this.videoIndex = index
      this.assignment(row)
    },

    // 抓拍图片
    async catchPhoto () {
      this.loading = true
      const params = {
        dataSign: 'TNT1603699784785-SERV1605252492314',
        endTime: 0,
        params: { ...this.eqptQueryParams },
        startTime: 0
      }
      try {
        const data = await eqptCommon(params)
        let res = JSON.parse(data.data)
        if (res.code === 0) {
          this.imgList.push(res.data.imageUrl)
          this.loading = false
        }
      } catch (error) {
        this.loading = false
      }
    },

    // 取消
    handleCancel () {
      this.dialogVisible = false
      this.loading = false
      this.showPlayer = false
      this.videoIndex = 0
      this.eqptList = []
      this.imgList = []
      this.activeEqptId = ''
      this.$set(this.playerOptions.sources[0], 'src', '')
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog-device-info {
  .no-video {
    display: flex;
    height: 200px;
    border: 1px solid #eee;
    align-items: center;
    justify-content: center;
    a {
      font-size: 16px;
      color: #aaa;
    }
  }
  .video-bar {
    padding-top: 15px;
    color: #aaaaaa;
    width: 100%;
    li {
      display: inline-block;
      cursor: pointer;
      padding: 2px 10px;
      border: 1px solid #5d6167;
      margin-right: 5px;
      margin-bottom: 8px;
      border-radius: 0px;
      &.active {
        border: 1px solid #409eff;
      }
    }
  }
  .catchBtn {
    margin-top: 10px;
  }
  .img-con {
    margin-top: 15px;
    .monitor-img {
      width: 80px;
      height: 80px;
      cursor: pointer;
      border-radius: 6px;
      margin-right: 10px;
      border: 1px solid #c0ccda;
      &:hover {
        border-color: #409eff;
      }
    }
  }
}
</style>
